<?php namespace App\Http\Services;

use Requests;
use Requests_Exception;

class YunPian
{
//    private $apiKey = 'be826f2f95930ef12d0474de26ab5902';
//    private $baseUrl = 'https://sms.yunpian.com/v2';
//    private $sendSmsUrl = '/sms/single_send.json';
//    private $sendTplSmsUrl = '/sms/tpl_single_send.json';
    private $apiKey = '34dfd103960439d08d11829e85615611';
    private $baseUrl = 'http://sms.haotingyun.com/v2';
    private $sendSmsUrl = '/sms/single_send.json';
    private $sendTplSmsUrl = '/sms/tpl_single_send.json';

    public function sendSms($sendTo, $content)
    {
        $result = self::doPost($this->sendSmsUrl, [
            'apikey' => $this->apiKey,
            'mobile' => $sendTo,
            'text'   => $content,
        ]);
        return $result;
    }

    public function sendBasicSmsWithCode($sendTo,$code)
    {
        $result = self::doPost($this->sendTplSmsUrl, [
            'apikey'    => $this->apiKey,
            'mobile'    => $sendTo,
            'tpl_id'    => 3212938,
            'tpl_value' => "#code#=".$code,
        ]);
        return $result;
    }

    private function doPost($url, array $param)
    {
        $response = null;
        try {
            $response = Requests::post($this->baseUrl . $url, [
                'Accept'       => 'text/plain;charset=utf-8',
                'Content-Type' => 'application/x-www-form-urlencoded;charset=utf-8',
            ], $param);
        } catch (Requests_Exception $ex) {
            Log::error('Request Error To YunPian:'.$ex);
        }

        if (!$response->success) {
            return false;
        }

        $res = json_decode($response->body);
        if (is_null($res))
            return false;

        return $res;
    }
}
